package org.roan.nettyclient.listener;

import io.netty.handler.codec.string.StringDecoder;
import org.roan.nettyclient.handler.LoginListener;
import org.roan.nettyclient.handler.NettyHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

@Slf4j
@Component
public class NettyClient implements ApplicationListener<ApplicationStartedEvent> {

    @Value("${netty.server.port}")
    private int nettyServerPort;

    @Autowired
    private NettyHandler nettyHandler;

    @Autowired
    private LoginListener loginListener;

    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        InetAddress localHost;
        try {
            localHost = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addFirst(new LoggingHandler());
                        ch.pipeline().addFirst(new StringEncoder());

                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new LoggingHandler());
                        ch.pipeline().addLast(nettyHandler);

                    }
                })
                .connect(localHost, nettyServerPort)
                // run listener after startup
                .addListener(loginListener);
    }
}
